package doc

import (
	"context"
	"strconv"

	"mall/common/errorx"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/rpc/backendclient"
	"mall/service/blog/rpc/blogclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type DocumentDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDocumentDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DocumentDetailLogic {
	return &DocumentDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DocumentDetailLogic) DocumentDetail(req *types.DocumentDetailRequest) (resp *types.DocumentDetailResponse, err error) {
	if req.Id == 0 {
		return nil, errorx.Error(errorx.ERROR_BLOG_POST_ID_REQUIRED, "")
	}

	detail, err := l.svcCtx.BlogRpc.BackendGetKBPostById(l.ctx, &blogclient.KBPostIdReq{
		Id: uint64(req.Id),
	})
	if err != nil {
		return nil, err
	}

	var userName string
	if detail.AuthorId != nil && *detail.AuthorId > 0 {
		userList, err := l.svcCtx.BackendRpc.BackendGetUserList(l.ctx, &backendclient.UserListRequest{
			UserIds: strconv.FormatUint(*detail.AuthorId, 10),
		})
		if err != nil {
			return nil, err
		}
		if userList.Total > 0 {
			userName = userList.List[0].Name
		}
	}

	var tags []*types.PostTag
	if len(detail.Tags) > 0 {
		for _, t := range detail.Tags {
			tags = append(tags, &types.PostTag{
				Id:   int64(*t.Id),
				Name: *t.Name,
				Slug: *t.Slug,
			})
		}
	}
	var sections []*types.PostCategory
	if len(detail.Sections) > 0 {
		for _, s := range detail.Sections {
			sections = append(sections, &types.PostCategory{
				Id:   int64(*s.Id),
				Name: *s.Name,
				Slug: *s.Slug,
			})
		}
	}

	return &types.DocumentDetailResponse{
		Status:  "ok",
		Message: "",
		Data: &types.Document{
			Id:          int64(*detail.Id),
			Title:       *detail.Title,
			ContentHtml: *detail.Content,
			CreatedBy:   userName,
			CreatedAt:   *detail.CreatedAt,
			UpdatedAt:   *detail.UpdatedAt,
			Sections:    sections,
			Tags:        tags,
		},
	}, nil
}
